<?php
class EWebby_Data_MySql_MySqlCommand implements EWebby_Data_IDbCommand {
	private $_conn;
	public $commandText;
	public $parameters;
	
	public function __construct($conn) {
		$this->_conn = $conn;
	}
	
	public function getSafeText($text) {
		return @mysql_real_escape_string ( $text, $this->_conn->getConnection() );
	}
	
	public function getSqlStatement() {
		return $this->_getSqlStatement ($this->_conn->getConnection());
	}
	private function _getSqlStatement($conn) {
		$safe_array = array ();
		if( is_array($this->parameters) ) {
			foreach ( $this->parameters as $paramValue ) {
				$safe_array [] = @mysql_real_escape_string ( $paramValue, $conn );
			}
		}
		
		return vsprintf ( $this->commandText, $safe_array );
	}
	
	private function _execute($conn) {
		$query = $this->_getSqlStatement ($conn);
		$result = @mysql_query ( $query, $conn );
		if( $result == null ) {
			throw new EWebby_Data_DbException("failed to execute the following query [$query] error:\n" . mysql_error ());
		}
		
		return $result;
	}
	
	public function executeNonQuery() {
		$conn = $this->_conn->getConnection();
		$this->_execute($conn);

		return @mysql_affected_rows ( $conn );
	}
	
	public function executeScalar() {
		$conn = $this->_conn->getConnection();
		$result = $this->_execute($conn);
		$row = @mysql_fetch_row ( $result );
		if ($row != null) {
			$value = $row [0];
			@mysql_free_result ( $result );
			
			return $value;
		}
		
		return null;
	}
	
	public function executeReader() {
		$conn = $this->_conn->getConnection();
		$result = $this->_execute($conn);
		
		return new EWebby_Data_MySql_MysqlReader($conn, $result );
	}
}